<?php

namespace App\Models\Archive\Migration;

use App\Models\Common\ArchiveCatalog;
use App\Models\Common\BaseMigration;
use Illuminate\Database\Schema\Blueprint;
use Psr\Log\LoggerInterface;
use function app;

class OperationLogsTable extends BaseMigration
{
    const TABLE_NAME = 'operation_logs';
    protected $connection = self::DB_CONN;
    const SPLIT_MODE = self::SPLIT_MODE_OPTION_YEAR;

    public function up(string $tableName): bool
    {
        $success = false;

        try {
            $conn = \Schema::connection($this->connection);

            if (!$conn->hasTable($tableName)) {
                $conn->create($tableName, function (Blueprint $table) {
                    $table->uuid('id')->primary();
                    $table->uuid('loggable_id')->default('');
                    $table->string('loggable_type')->default('');
                    $table->string('loggable_name', 50)->default('');
                    $table->uuid('parking_lot_id')->default('');
                    $table->string('parking_lot_name', 50)->default('');
                    $table->string('source', 50)->default('');
                    $table->bigInteger('login_ip')->default(0);
                    $table->string('type', 50)->default('');
                    $table->string('content')->default('');
                    $table->string('keyword', 50)->default('')->index('idx_keyword');
                    $table->timestamps();
                    $table->index(['loggable_id', 'loggable_type'], 'idx_loggable');
                    $table->index(['parking_lot_id', 'loggable_id', 'type', 'source', 'created_at'], 'combo_idx_parking_lot');
                });
            }
            $success = true;
        } catch (\Throwable $exception) {
            app(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'act' => '创建操作日志']);
        } finally {
            try {
                $success && ArchiveCatalog::insertOrIgnore(['name' => $tableName, 'id' => \Str::orderedUuid()->toString()]);
            } catch (\Throwable $exception) {
                app(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'act' => '更新存档菜单表']);
            }
        }
        return $success;
    }
}
